﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Solution.Data;
using Solution.Business.Infrastructure;
using System.Web.Security;
using Solution.Utilities;
using Solution.Utilities.Security;
using System.Configuration;
using Solution.Business;

namespace Solution.Mvc.Areas.Admin.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Admin/Login/

        [HttpGet]
        public ActionResult Index()
        {
            ViewBag.Mess = "";
            string ReturnUrl = Request.QueryString["ReturnUrl"];
            if (string.IsNullOrEmpty(ReturnUrl))
                ReturnUrl = Url.Action("index", "admin");
            ViewBag.ReturnUrl = HttpUtility.UrlEncode(ReturnUrl);
            if (Request.ServerVariables["HTTP_COOKIE"] == null)
            {
                ViewBag.Mess = "<strong>No cookies? You can not login if your browser turn off cookie <a href=\"http://support.google.com/accounts/bin/answer.py?hl=en&answer=61416\">read to turn on cookie</a></strong>";
            }
            return View();
        }
        [HttpPost]
        public ActionResult Index(string username, string password, string ReturnUrl, bool remember, FormCollection cl)
        {
            username = UtilCommon.FilterStringSpecialCharacter(username, true, null);
            password = UtilCommon.FilterStringSpecialCharacter(password, true, null);
            if (string.IsNullOrEmpty(ReturnUrl))
                ReturnUrl = HttpUtility.UrlDecode(Url.Action("index", "admin"));
            else
                ReturnUrl = HttpUtility.UrlDecode(ReturnUrl);
            int _authen = Authenticate(username, password);
            ViewBag.Mess = "";
            switch (_authen)
            {
                case 0:
                    ViewBag.Mess = "Account not found";
                    return View();
                case 1:
                    ViewBag.Mess = "Your account has been deleted";
                    return View();
                case 2:
                    ViewBag.Mess = "Your account has been locked";
                    return View();
                case 3:
                    var logonUser = new UserBLL().GetOne(username);
                    DoLogin(logonUser, remember);
                    return Redirect(ReturnUrl);
                default: return View();
            }

        }
        public JsonResult LogOff()
        {
            try
            {
                this.ExpireCookie(".ASPXAUTH");
                this.ExpireCookie("SqlAuthCookie");
                Session.Clear();
                Session.Abandon();
                return Json("ok", JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json("err", JsonRequestBehavior.AllowGet);
            }
        }
        private int Authenticate(string username, string password)
        {

            ViewData["ErrorDetails"] = string.Empty;
            var fieldAuthenticated = true;
            if (String.IsNullOrEmpty(username))
            {
                fieldAuthenticated = false;
            }
            if (String.IsNullOrEmpty(password))
            {
                fieldAuthenticated = false;
            }
            if (!fieldAuthenticated)
            {
                ViewData["ErrorDetails"] = "The username or password provided is incorrect or user is logged in.";
            }
            return LoginOk(username, password);

        }
        private int LoginOk(string username, string password)
        {
            try
            {
                if (username == null)
                    throw new ArgumentNullException("userName");

                if (username == string.Empty)
                    throw new ArgumentException("userName");

                if (password == null)
                    throw new ArgumentNullException("password");

                if (password == string.Empty)
                    throw new ArgumentException("password");
                return new UserBLL().Login(username, password);
            }
            catch { return 0; }
        }

        [NonAction()]
        private void DoLogin(User user, bool remember)
        {
            var timeOut = 400;
            UserData ud = new UserData(user.Id, user.LoginName);
            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, user.LoginName, DateTime.Now, DateTime.Now.AddMinutes(timeOut), remember, ud.ToXml());
            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
            HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            if (remember)
                authCookie.Expires = DateTime.Now.AddMonths(1);
            Response.Cookies.Add(authCookie);
        }
        [NonAction()]
        private void ExpireCookie(string cookieName)
        {
            if (Request.Cookies[cookieName] != null)
            {
                HttpCookie cookie = new HttpCookie(cookieName);
                cookie.Expires = DateTime.Now.AddDays(-1d);
                Response.Cookies.Add(cookie);
            }
        }
    }
}
